#coding=utf8
#LightCam 处理snmpinterface.txt程序
#init by hfh 20150608

import time,re,sys,traceback,threading,subprocess,pymongo,json,os
import lc_libs

if __name__ == "__main__":


	lchome=lc_libs.lc_getlchome()
	scname=sys.argv[0].split('.')[0]
	logfilename=lchome+'/log/'+scname+'.log'
	confname=lchome+'/conf/'+scname+'.conf'
	
	today=time.strftime('%Y%m%d',time.localtime())
	os.system("mv %s %s.%s" % (logfilename,logfilename,today))
	
	logfile=file(logfilename,'a')
	logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
	logfile.write(logdate+" Started.\n")
	logfile.flush()
	
	try:
		#初始化数据库
		db=lc_libs.lc_mongodb_operater('127.0.0.1',27017)

		db.connect()
		Conn=db.getConn()
		if Conn==None:
			print "Can not Connect to the MondbDB"
			exit(0)
		
		perf_dbname='lc_perf'
		vipport_tablename='lc_vipport'
		
		perf_db=db.useDatabase(perf_dbname)
		vipport_table=db.UseCollection(perf_db,vipport_tablename)

	except Exception:
		excinfo=traceback.format_exc()
		logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
		logfile.write(logdate+" 初始化数据库失败:\n"+excinfo+"\n")
		logfile.flush()
		exit(0)
		
	portlist=[
		['172.26.254.141','Gi5/6'],
		['172.26.254.142','Gi5/6'],
		['172.26.254.31','Gi5/5'],
		['172.26.254.31','Gi5/6'],
		['172.26.254.32','Gi5/5'],
		['172.26.254.32','Gi5/6'],
		['172.26.254.33','Gi5/5'],
		['172.26.254.33','Gi6/5'],
		['172.26.254.34','Gi5/5'],
		['172.26.254.34','Gi6/5'],
		['172.26.254.37','Gi5/3'],
		['172.26.254.38','Gi5/3'],
		['172.26.254.53','Gi1/46'],
		['172.26.254.54','Gi1/46'],
		['172.26.254.7','Gi1/48'],
		['172.26.254.8','Gi1/48']
	]
	
	#timelist=['08:00','08:30','09:00','09:30','10:00','10:30','11:00','11:30','12:00','12:30','13:00','13:30','14:00','14:30','15:00','15:30','16:00','16:30','17:00']
	#timelist=['16:43','16:44','16:45','16:46','16:47','16:48','16:49','16:50','16:51','16:52','16:53','16:54','16:55','16:56','16:57','16:58','16:59']

	############### init timelist ##############################
	starttime=time.mktime(time.strptime('08:30','%H:%M'))
	endtime=time.mktime(time.strptime('17:00','%H:%M'))
	
	thistime=starttime
	timelist=[]
	i=0
	while True:
		thistime=thistime+i
		i=300
		thistimestr=time.strftime('%H:%M',time.localtime(thistime))
		timelist.append(thistimestr)
		if thistime==endtime:
			break
		else:
			time.sleep(0.01)
			
	print timelist
	############################################
	
	today=time.strftime('%Y%m%d',time.localtime())
		
	while True:
		time.sleep(1)
		try:
			now=time.strftime('%H:%M',time.localtime())
			print now
			
			if now not in timelist:
				time.sleep(60)
				continue
			else:
				print "%s it is the time to run" % now
			
			if now=='08:30':
				print "Drop db"
				perf_db.drop_collection(vipport_tablename)
				comd="cp %s/pyweb/static/json/vipport/lc_vipport.json %s/pyweb/static/json/vipport/history/%s.json" % (lchome,lchome,today)
				popen=subprocess.Popen(comd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
				today=time.strftime('%Y%m%d',time.localtime())
			
			#logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
			#logfile.write("%s run \n" % logdate)
			#logfile.flush()
			
			comd="scp ywn_monitor1:/monitor/bin/network/snmp_interface.txt /tmp/"
			popen=subprocess.Popen(comd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
			while True:
				if popen.poll()==None:
					time.sleep(0.1)
					continue
				else:
					break
			
			ifile=open('/tmp/snmp_interface.txt','r')
			idata=ifile.readlines()
			ifile.close()
			
			idict=[]
			iport={}
			key=''
			value=''
			
			for lines in idata:
				if 'Device=' in lines and len(iport)<>0:
					try:
						Device=iport['Device']
						ifName=iport['ifName']
					except Exception:
						pass
						#print traceback.format_exc()
					if [Device,ifName] in portlist:
						indata={'Time':now,'Device':iport['Device'],'ifName':iport['ifName'],'RateInOctets':iport['RateInOctets']}
						idict.append(indata)
					new=int(time.time())
					iport={}
					
				if len(iport)==0:
					new=int(time.time())
					iport={'LCTime':new}
						
				key=lines.split('=')[0].strip('\r\n\t')
				value=lines.split('=')[1].strip('\r\n\t')
				if key=='ifDescr':
					key='ifDesc'
				iport[key]=value
				
			try:
				if [iport['Device'],iport['ifName']] in portlist:
					indata={'Time':now,'Device':iport['Device'],'ifName':iport['ifName'],'RateInOctets':iport['RateInOctets']}
					idict.append(indata)
			except Exception:
				pass
				#print traceback.format_exc()
			
			for iport in idict:
				#print iport
				db.insertDatas(vipport_table,iport)
	
	
			###########生成json文件######################
			jdata=[]
			for line in portlist:
				
				Device=line[0]
				ifName=line[1]
				name="%s %s" % (Device,ifName)
				
				rowdata=[]
				expr={"Device":Device,"ifName":ifName}
				sortcont=[("Time",pymongo.ASCENDING)]
				opts=db.queryData(vipport_table,expr,sortcont,200)
				res=db.genResult(opts)
				for line in res:
					rowdata.append(float(line['RateInOctets']))
				jdata.append({'name':name,'data':rowdata})
			
			#print json.dumps(jdata)
			file=open(lchome+"/pyweb/static/json/vipport/lc_vipport.json",'w')
			file.write(json.dumps(jdata))
			file.close()
			
			file=open(lchome+"/pyweb/static/json/vipport/lc_vipport_time.json",'w')
			file.write(json.dumps(timelist))
			file.close()
			#########################################
		except Exception:
			excinfo=traceback.format_exc()
			logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
			logfile.write(logdate+" \n"+excinfo+"\n")
			logfile.flush()
		
		time.sleep(60)
